from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import date, datetime
from typing import List, Dict, Optional, Union
from backend.service.load_data_service import LoadDataService
from backend.config.database import get_db
from backend.utils.timezone_utils import parse_date_string_utc, validate_date_range, get_timezone_info
from pydantic import BaseModel

router = APIRouter(prefix="/load", tags=["电力负载数据"])

class MetricsResponse(BaseModel):
    avg: float
    peak: float
    valley: float
    timestamp: str

class LoadDataResponse(BaseModel):
    date: str
    values: Dict[str, Optional[float]]  # 允许None值
    metrics: MetricsResponse  # 使用专门的metrics模型

@router.get("/date/{target_date}", response_model=LoadDataResponse)
async def get_by_date(
    target_date: str,
    db: Session = Depends(get_db)
):
    """精确日期查询（带自动指标计算）"""
    try:
        # 使用UTC时区工具解析日期
        target_date_obj = parse_date_string_utc(target_date)
        if not target_date_obj:
            raise HTTPException(status_code=400, detail="日期格式错误，请使用YYYY-MM-DD格式")
        
        data_list = LoadDataService.get_load_data_by_date(db, datetime.combine(target_date_obj, datetime.min.time()))
        if not data_list:
            raise HTTPException(
                status_code=404,
                detail=f"未找到{target_date}的负荷数据"
            )

        # 构建兼容旧格式的values字典
        values = {}
        for record in data_list:
            if record.t_idx and 1 <= record.t_idx <= 96:
                values[f"t{record.t_idx}"] = float(record.load_val) if record.load_val is not None else None

        return {
            "date": target_date,
            "values": values,
            "metrics": LoadDataService.calculate_metrics(data_list)
        }
        
    except ValueError as e:
        raise HTTPException(
            status_code=400,
            detail=f"日期格式错误，请使用 YYYY-MM-DD 格式: {str(e)}"
        )
    except Exception as e:
        import traceback
        error_detail = f"查询负荷数据时发生错误: {str(e)}\n详细错误:\n{traceback.format_exc()}"
        print(f"API错误 (get_by_date): {error_detail}")  # 添加控制台输出
        raise HTTPException(
            status_code=500,
            detail=error_detail
        )

@router.get("/period", response_model=List[LoadDataResponse])
async def get_by_period(
    start_date: str = Query(..., description="开始日期，格式：YYYY-MM-DD"),
    end_date: str = Query(..., description="结束日期，格式：YYYY-MM-DD"),
    db: Session = Depends(get_db)
):
    """时间段批量查询"""
    try:
        # 使用UTC时区工具验证日期范围
        validation = validate_date_range(start_date, end_date, max_days=365)
        if not validation["valid"]:
            raise HTTPException(status_code=400, detail=validation["message"])
        
        start_date_obj = validation["start_date"]
        end_date_obj = validation["end_date"]
        
        result = []
        # 按日期循环查询每一天的数据
        current_date = start_date_obj
        while current_date <= end_date_obj:
            daily_records = LoadDataService.get_load_data_by_date(db, datetime.combine(current_date, datetime.min.time()))
            
            if daily_records:
                # 构建兼容旧格式的values字典
                values = {}
                for record in daily_records:
                    if record.t_idx and 1 <= record.t_idx <= 96:
                        values[f"t{record.t_idx}"] = float(record.load_val) if record.load_val is not None else None
                
                result.append({
                    "date": current_date.isoformat(),
                    "values": values,
                    "metrics": LoadDataService.calculate_metrics(daily_records)
                })
            
            current_date += timedelta(days=1)
        
        if not result:
            raise HTTPException(
                status_code=404,
                detail=f"在{start_date}到{end_date}期间未找到负荷数据"
            )
        
        return result
        
    except ValueError as e:
        raise HTTPException(
            status_code=400,
            detail=f"日期格式错误，请使用 YYYY-MM-DD 格式: {str(e)}"
        )
    except Exception as e:
        import traceback
        error_detail = f"查询负荷数据时发生错误: {str(e)}\n详细错误:\n{traceback.format_exc()}"
        print(f"API错误 (get_by_period): {error_detail}")  # 添加控制台输出
        raise HTTPException(
            status_code=500,
            detail=error_detail
        )
